package com.ddj.algorithm.quicksort;

public class QuickSort {

    /**
     * 什么是快排：
     *           采用分治思想
     *           选择数组中最后一个数字作为基准数
     *           左侧全是小于基准数，
     *           右侧大于基准数
     *           进行递归
     * @param args
     */
    public static void main(String[] args) {
        int[] testData = new int[]{3, 32, 12, 7, 99, 2, 32, 999, 21};
        quickSort(testData, 0, testData.length - 1);
        for (int item : testData) {
            System.out.print(item + " ");
        }
    }

    public static void quickSort(int[] arr, int left, int right) {
        if (left >= right) {
            return;
        }
        int pivot = partition(arr, left, right);
        quickSort(arr, left, pivot - 1);
        quickSort(arr, pivot + 1, right);
    }

    public static int partition(int[] arr, int left, int right) {
        int pivot = arr[right];
        int i = left - 1;
        for (int j = left; j < right; j++) {
            if (arr[j] < pivot) {
                i++;
                swap(arr, i, j);
            }
        }
        swap(arr, i + 1, right);
        return i + 1;
    }

    public static void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

}
